//
//  TravelListViewController.m
//  Haliaeetus
//
//  Created by junli hou on 2018/3/20.
//  Copyright © 2018年 BMY. All rights reserved.
//

#import "TravelListViewController.h"
#import "UIView+KaleMallView.h"
#import "TraveListTableViewCell.h"
#import "SVProgressHUD.h"
#import "TravelDetialViewController.h"
@interface TravelListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, strong) UIImageView *emptyImage;
@property (nonatomic, strong) UILabel *detail;
@property (nonatomic, strong) UIButton *refreshBtn;
@property (nonatomic, assign) int current_page;
@property (nonatomic, strong) NSMutableArray *travelListArray;
@end
@implementation TravelListViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
        self.title=@"行程";
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshAction) name:@"reloadList"object:Nil];
    self.view.backgroundColor = WS_RGB(242, 242, 242);

    
    self.travelListArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[TraveListTableViewCell class] forCellReuseIdentifier:@"TraveListTableViewCell"];
    self.current_page=1;
    
    
    
    
    
    //需要登录
    if(![LoginManager getUserLoginStatus]) {

    }else{
           self.current_page=1;
        //请求数据源
        [self getTravelListData];
        [self addFooter];
        [self addHeader];
    }
    

}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height-49)style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = WS_RGB(246, 246, 246);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}

- (UIView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [UIView new];
        _emptyView.backgroundColor = [UIColor whiteColor];
        _emptyView.frame = self.view.bounds;
        [self.view addSubview:_emptyView];
        
        self.emptyImage = [[UIImageView alloc]init];
        self.emptyImage.image = [UIImage imageNamed:@"empty_icon"];
        self.emptyImage.size = CGSizeMake(160,160);
        self.emptyImage.centerX = self.view.centerX ;
        self.emptyImage.y = self.view.centerY/2 - 40;
        [_emptyView addSubview:self.emptyImage];
        
        self.detail = [UILabel new];
        self.detail.frame = CGRectMake(0,CGRectGetMaxY(self.emptyImage.frame) + 10,WS_SCREEN_FRAME_WIDTH,15);
        self.detail.font = [UIFont systemFontOfSize:13];
        self.detail.textColor = WS_RGB(204,204,204);
        self.detail.textAlignment = NSTextAlignmentCenter;
        [_emptyView addSubview:self.detail];
        
        self.refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.refreshBtn.size = CGSizeMake(120,35);
        self.refreshBtn.centerX = self.view.centerX ;
        self.refreshBtn.y = CGRectGetMaxY(self.emptyImage.frame);
        self.refreshBtn.layer.borderWidth = 1;
        self.refreshBtn.layer.borderColor = WS_RGB(153, 153, 153).CGColor;
        [self.refreshBtn setTitle:@"点击刷新" forState:UIControlStateNormal];
        [self.refreshBtn setTitleColor:WS_RGB(153, 153, 153) forState:UIControlStateNormal];
        self.refreshBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.refreshBtn addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
        [_emptyView addSubview:self.refreshBtn];
        self.refreshBtn.hidden = YES;
    }
    return _emptyView;
}

- (void)refreshAction
{
    [self.emptyView removeFromSuperview];
    self.emptyView = nil;
       self.current_page=1;
    [self addFooter];
    [self addHeader];
    [self getTravelListData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}
//- (void)viewDidDisappear:(BOOL)animated
//{
//    [self.navigationController.navigationBar setBackgroundImage:[WSTool imageWithColor:WS_RGBA(104, 163, 251, 1) andHeight:1.0] forBarMetrics:UIBarMetricsDefault];
//    [super viewDidDisappear:animated];
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    //需要登录
    if(![LoginManager getUserLoginStatus]) {
        LoginViewController *loginController = [[LoginViewController alloc] initWithLoginSuccessBlock:^{
            self.current_page=1;
            [self getTravelListData];
            [self addFooter];
            [self addHeader];
             self.tableView.hidden = NO;
        } :^{
            
            self.tabBarController.selectedIndex=0;
            
        }];
        [self presentViewController:[[BaseNavigationController alloc] initWithRootViewController:loginController] animated:YES completion:nil];
    }else{
    }
    
}

-(void)addHeader{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        self.current_page=1;
        [self.travelListArray removeAllObjects];
        [self getTravelListData];
    }];
}

-(void)addFooter{
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.current_page++;
        [self getTravelListData];
    }];
    
    [footer setTitle:@"没有更多了" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;
}


- (void)getTravelListData
{

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[NSString stringWithFormat:@"%d",self.current_page] forKey:@"page"];
    [params setObject:[NSString stringWithFormat:@"%d",10] forKey:@"per_page"];
    
        
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/schedules"] params:NULL onCompletion:^(NSMutableDictionary *dic){
            [SVProgressHUD dismiss];
            
            if ([[dic objectForKey:@"biz_action"] intValue] == 0) {
                self.tableView.hidden = NO;
                 [self.tableView.mj_header endRefreshing];
                NSMutableArray *array = [[dic objectForKey:@"data"] objectForKey:@"schedules"];
                if (array.count > 0) {
                    [self.travelListArray addObjectsFromArray:array];
                    [self.tableView reloadData];
                    if ([[[dic objectForKey:@"data"] objectForKey:@"total"] intValue]>self.current_page) {
                         [self.tableView.mj_footer endRefreshing];
                    }else{
                      
                         [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }else{
                    self.tableView.hidden = YES;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    [self.view addSubview:self.emptyView];
                    self.emptyImage.image  = [UIImage imageNamed:@"empty_icon"];
                    self.detail.text = @"暂无行程信息";
                }
            }else{
                
                //请求出错
                WSToast([dic objectForKey:@"biz_msg"]);
            }
        } onError:^(NSError *error) {
            
            if (error.code==99999) {
                WSToast(@"网络异常，请检查网络设置!");
            }
            [SVProgressHUD dismiss];
            
        }];

}
#pragma mark - UITableViewSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.travelListArray.count ;
//    return 3 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


        TraveListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TraveListTableViewCell"];
        NSDictionary *dic = [self.travelListArray objectAtIndex:indexPath.row];
//        //title
//        cell.hotelNameLab.text = [NSString stringWithFormat:@"%@,%@",[dic objectForKey:@"place_name"],[dic objectForKey:@"city_name"]];
//        //vp
//        cell.timeLab.text = [NSString stringWithFormat:@"%@ - %@",[dic objectForKey:@"check_in_date"],[dic objectForKey:@"check_out_date"]];
    
    cell.cityName.text=[NSString stringWithFormat:@"%@,%@",WS_STR_NOT_NULL([dic objectForKey:@"country"]),WS_STR_NOT_NULL([dic objectForKey:@"city_name"])];
    cell.spaceName.text= [NSString stringWithFormat:@"%@,%@",WS_STR_NOT_NULL([dic objectForKey:@"place_name"]),@""];
    cell.checkInDate.text=[NSString stringWithFormat:@"%@",WS_STR_NOT_NULL([dic objectForKey:@"check_in_date"])];
    cell.checkoOutDate.text=[NSString stringWithFormat:@"%@",WS_STR_NOT_NULL([dic objectForKey:@"check_out_date"])];
    return cell;

}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

        return 240;

    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
        NSDictionary *dic = [self.travelListArray objectAtIndex:indexPath.row];
    TravelDetialViewController *travelDetialViewController=[[TravelDetialViewController alloc]init];
    travelDetialViewController.hidesBottomBarWhenPushed=YES;
    travelDetialViewController.dic=dic;
    [self.navigationController pushViewController:travelDetialViewController animated:YES];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
